<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-07-05 17:55:56
 * @Description: 租户、门店登录验证
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-09-16 09:56:29
 * @FilePath: /qingshanERP/app/Http/Middleware/TenantJwt.php
 */
namespace App\Http\Middleware;

use App\Customize\Sign;
use Closure;
use Illuminate\Support\Facades\Redis as Redis;

class TenantJwt {
	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next) {
		try {
			// 先验证签名
			$res = Sign::aes_decrypt($request->all());
			if ($res['code'] != 200) {
				return response()->json(['code' => 403, 'msg' => $res['msg'] . '...', 'data' => []]);
			}
			// 合并解析到的参数进请求中
			$request->merge($res['data']);
			// 验证 token
			$token = $request->header('Authorization');
			if (is_null($token) || $token == '') {
				return response()->json(['code' => 401, 'msg' => '请重新登录，获取验证信息...', 'data' => $token]);
			}
			// 查有没有这个用户，及用户状态
			$hav = Redis::exists('t-token:' . $token);
			if (!$hav) {
				return response()->json(['code' => 401, 'msg' => '验证信息无效，请重新登录...', 'data' => $token]);
			}
			$token_info = Redis::get('t-token:' . $token);
			// 解析用户信息，判断权限
			$user = json_decode($token_info);
			// 拼接权限名字，url的第二个跟第三个参数
			$toArr = explode('/', $request->path());
			if ($toArr[0] != 't-api') {
				return response()->json(['code' => 402, 'msg' => '无权调用此接口数据...', 'data' => '1']);
			}
            $request->tenant = $user;
            $response = $next($request);
            return $response;
		} catch (\Throwable $e) {
			return response()->json(['code' => 401, 'msg' => '验证权限失败...', 'data' => ''.$token]);
		}
	}
}
